package br.senai.sc.util.security;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;

import org.jboss.seam.international.status.Messages;
import org.jboss.seam.international.status.builder.BundleKey;
import org.jboss.seam.security.BaseAuthenticator;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;
import org.picketlink.idm.api.Credential;
import org.picketlink.idm.impl.api.PasswordCredential;

import br.senai.sc.controller.crud.UsuarioCRUD;
import br.senai.sc.model.Permissao;
import br.senai.sc.model.Usuario;

/**
 * Autenticador da aplicação. Executa a autenticação de um usuário e de suas devidas permissões.
 * 
 * @author Fernando Marquardt &lt;fernando.marquardt@sc.senai.br&gt;
 * @version $Id: ApplicationAuthenticator.java 28 2012-03-07 20:48:20Z fernando.marquardt $
 */
@Named
@RequestScoped
public class ApplicationAuthenticator extends BaseAuthenticator {

    @Inject
    private Credentials credentials;

    @Inject
    private Identity identity;

    @Inject
    private UsuarioCRUD usuarioCRUD;

    @Inject
    private Messages messages;

    /**
     * {@inheritDoc}
     */
    @Override
    public void authenticate() {
        String username = credentials.getUsername();
        String password = "";
        Credential credential = credentials.getCredential();

        if (credential instanceof PasswordCredential) {
            password = ((PasswordCredential) credential).getValue();
        }

        Usuario usuario = usuarioCRUD.findByLogin(username);

        if ((usuario != null) && usuario.getSenha().equals(password)) {
            setStatus(AuthenticationStatus.SUCCESS);
            setUser(new LoggedUser(usuario.getIdUsuario(), usuario.getNome()));

            Permissao permissao = usuario.getPermissao();

            if (permissao.isAdministracao()) {
                identity.addRole("administracao", "Permissoes", "Usuarios");
            }

            if (permissao.isCadastro()) {
                identity.addRole("cadastro", "Permissoes", "Usuarios");
            }

            if (permissao.isConsulta()) {
                identity.addRole("consulta", "Permissoes", "Usuarios");
            }

            messages.info(new BundleKey("br.senai.sc.i18n.CommonMessages", "login.sucesso"), usuario.getNome());
        } else {
            setStatus(AuthenticationStatus.FAILURE);
            messages.error(new BundleKey("br.senai.sc.i18n.CommonMessages", "login.loginSenhaInvalidos"));
        }
    }
}